package progress.exa38.io;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class IoStudy {

    public static String read(String path) throws IOException {
        Reader reader = new FileReader(path);
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuilder bf = new StringBuilder();
        String str;
        //阻塞式，在完成读操作之前，线程一直在这里停留
        while ((str = bufferedReader.readLine()) != null) {
            bf.append(str).append("\n");
        }
        bufferedReader.close();
        reader.close();
        return bf.toString();
    }

    /**
     * 传统服务器端的同步阻塞式IO处理
     * @throws IOException
     */
    public void normalServer() throws IOException {
        ExecutorService executor = Executors.newFixedThreadPool(100);//线程池

        ServerSocket serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress(8080));
        //主线程死循环等待新连接到来
        while (!Thread.currentThread().isInterrupted()) {
            Socket socket = serverSocket.accept();
            executor.submit(new ConnectIOnHandler(socket));//为新的连接创建新的线程
        }
    }


}

class ConnectIOnHandler extends Thread {

    private Socket socket;

    public ConnectIOnHandler(Socket socket){
        this.socket = socket;
    }

    public void run(){
        //死循环处理读写事件
        while(!Thread.currentThread().isInterrupted()&&!socket.isClosed()){
            String someThing = null;
            //someThing = socket.read();//读取数据
            if(someThing!=null){
             //处理数据
                //socket.write();//写数据
            }
        }
    }
}
